import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/collect_dao.dart';
import 'package:changxindianzishangwu/dao/emoji_list_dao.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/model/collect_list_model.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/checkbox_widget.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class MessageIconPage extends StatefulWidget {
  MessageIconPage({Key key}) : super(key: key);

  @override
  _MessageIconPageState createState() => _MessageIconPageState();
}

class _MessageIconPageState extends State<MessageIconPage> {
  bool ad = false;
  bool rightBar = true;

  @override
  void initState() {
    super.initState();
    getData();
  }

  List<Widget> widgetElse = [];
  List<Widget> widgetData = [];
  List emojiId = [];
  bool a = false;
  var file;
  eee() async {
    var file2 = await DefaultCacheManager().downloadFile(MESSAGE_BACKGROUND2);
    file = file2.file.path;
  }

  Future<int> getData() async {
    // var file = await DefaultCacheManager().downloadFile(MESSAGE_BACKGROUND2);
    // var file2 = await DefaultCacheManager().downloadFile(MESSAGE_BACKGROUND2);
    // if (file.file.path == file2.file.path) {
    //   showToast(file.file.path);
    // }

    CollectListModel collectListModel =
        await EmojiListDao.getEmojiList(getUserInfo().userId);
    if (collectListModel.resultCode == 1) {
      widgetData = [];

      collectListModel.data.forEach((element) {
        widgetData.add(
          InkWell(
              onTap: () async {
                if (!rightBar) {
                  int a = await CollectDao.collectDelete(element.emojiId);

                  if (a == 1) {
                    showToast("删除成功");
                  } else {
                    showToast("删除失败");
                  }
                  getData();
                }
              },
              child: Container(
                height: 55.w,
                width: 55.w,
                alignment: Alignment.topRight,
                margin: EdgeInsets.only(left: 18.w, top: 15),
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: CachedNetworkImageProvider(
                          element.url,
                        ),
                        fit: BoxFit.cover),
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(
                        width: 0.3,
                        color: ZdColor.rgba(214, 214, 214, 1),
                        style: BorderStyle.solid)),
                child: rightBar
                    ? Text("")
                    : Icon(
                        Icons.cancel,
                        size: 14.w,
                        color: Colors.deepOrange,
                      ),
              )),
        );
      });
    }
    setState(() {});
    return collectListModel.data.length;
  }

  @override
  void dispose() {
    super.dispose();
    EasyLoading.dismiss();
  }

  Widget checkWidget(element) {
    rightBar
        ? SizedBox()
        : Positioned(
            top: 31.w,
            left: 36.w,
            child: DefCheckBoxWidget(
              value: element.isSelect,
              onTap: (d) {
                if (d) {
                  emojiId.add(element.emojiId);
                } else {
                  emojiId.remove(element.emojiId);
                }
                setState(() {
                  element.isSelect = d;
                });
              },
            ),
          );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "表情管理",
          style: TextStyle(
            fontSize: ScreenUtil().setSp(16),
          ),
        ),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () {
              setState(() {
                rightBar = !rightBar;
              });
              getData();
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 11, bottom: 11, right: 15),
              height: 10,
              width: ScreenUtil().setWidth(60),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(
                rightBar ? "整理" : "完成",
                style: TextStyle(
                    color: Colors.black, fontSize: ScreenUtil().setSp(14)),
              ),
            ),
          )
        ],
      ),
      body: Container(
          height: double.infinity,
          width: double.infinity,
          child: Column(
            children: [
              Container(
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    Wrap(
                      children: widgetData,
                    ),
                  ],
                ),
              ),
              Container(
                  margin: EdgeInsets.only(bottom: 20, left: 20.w),
                  child: InkWell(
                    onTap: () async {
                      bool status = await Permission.storage.isGranted;
                      //判断如果还没拥有读写权限就申请获取权限
                      if (!status) {
                        return await Permission.storage.request().isGranted;
                      }
                      // Dio dio = new Dio();
                      // dio.download(HEADER_URL, "/storage/emulated/0/test.png");
                      if (rightBar) {
                        final pickedFile = await ImagePicker()
                            .getImage(source: ImageSource.gallery);

                        Map<String, dynamic> map = Map();

                        map["file"] = await MultipartFile.fromFile(
                            pickedFile.path,
                            filename:
                                "heard${new DateTime.now().millisecondsSinceEpoch}.png");
                        EasyLoading.show(status: "正在上传中...");
                        FormData formData = FormData.fromMap(map);

                        DynamicMediaModel model =
                            await UpLoadFileDao.addFile(formData);
                        if (model.resultCode == 1) {
                          int a = await getData();
                          if (a > 20) {
                            EasyLoading.dismiss();
                            showToast("最多只能添加20个表情");
                          } else {
                            var result = await CollectDao.addCollect(
                                "", "6", model.data.images[0].oUrl,
                                roomJid: "0", emoji: "");
                            if (result['resultCode'] == 1) {
                              getData();
                              EasyLoading.dismiss();
                              setState(() {});
                            }
                          }
                        }
                      }
                    },
                    child: rightBar
                        ? Container(
                            alignment: Alignment.center,
                            margin:
                                EdgeInsets.only(top: 22, bottom: 11, right: 15),
                            height: 40,
                            width: ScreenUtil().setWidth(60),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(6),
                              color: Color.fromRGBO(0, 220, 169, 1),
                            ),
                            child: Text(
                              "添加",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setSp(14)),
                            ),
                          )
                        : SizedBox(),
                  )),
              Container(
                height: MediaQuery.of(context).padding.bottom,
              ),
            ],
          )),
    );
  }
}
